import Taro from "@tarojs/taro";
import {
  View, Image, Picker, ScrollView
} from "@tarojs/components";
import "./index.scss";
import { useState, useEffect } from "react";
import IconFont from "@/components/iconfont";
import { SwiperContainer } from "@/components/swiper";
import { IConfigIcons, IBanner, IVideo, ISchool, IWork, IWorkType } from "./config";
import { queryBanners, queryVideos, querySchools, queryWorks, queryWorksType, queryUserInfo } from "./api";
import { useSelector } from "react-redux";
import { ISystemConfig, ISubject } from "@/packages/package-system/config";
import { queryHomeTypeList, querySubjects } from "@/packages/package-system/api";

const Index = () => {

  const [schoolId, setSchoolId] = useState(-1)

  const [schools, setSchools] = useState<ISchool[]>([])

  const [works, setWorks] = useState<IWork[]>([])

  const [worksType, setWorksType] = useState<IWorkType[]>([])

  const [banners, setBanners] = useState<IBanner[]>([])
  const [videos, setVideos] = useState<IVideo[]>([])

  const { login } = useSelector((state: any) => state.login);

  const [paintData, setPaintData] = useState<any[][]>([
    [], []
  ])

  const [shufaData, setShufaData] = useState<any[][]>([
    [], []
  ])

  const [jiaopeiData, setJiaoPeiData] = useState<any>([
    [], []
  ])

  const [homeTypes, setHomeTypes] = useState<any[]>([])

  useEffect(() => {
    if (!login) {
      setTimeout(() => {
        Taro.navigateTo({
          url: '/packages/package-login/index'
        })
      }, 1500);
    } else {
      queryUserInfo().then((res: any) => {
        if (res) {
          Taro.setStorageSync('type', res.type)
        }
      })
      getHomeTypes()
    }
  }, [login])


  useEffect(() => {
    queryBanners({ pageNum: 1, pageSize: 100, schoolId }).then((res: Common.Response.BaseListData<IBanner>) => {
      if (res) {
        setBanners(res.items)
      }
    })
    queryVideos({ pageNum: 1, pageSize: 100, schoolId }).then((res: Common.Response.BaseListData<IVideo>) => {
      if (res) {
        setVideos(res.items)
      }
    })
    querySchools({ pageNum: 1, pageSize: 100, schoolId }).then((res: Common.Response.BaseListData<ISchool>) => {
      if (res) {
        setSchools([{ id: -1, schoolName: '全部校区', createTime: 1 }, ...res.items])
      }
    })
    queryWorks({ pageNum: 1, pageSize: 4, schoolId }).then((res: Common.Response.BaseListData<IWork>) => {
      if (res) {
        setWorks(res.items)
      }
    })
    queryWorksType({ pageNum: 1, pageSize: 100 }).then((res: Common.Response.BaseListData<IWorkType>) => {
      if (res) {
        setWorksType(res.items)
      }
    })
    Taro.setStorageSync('schoolId', schoolId)
  }, [schoolId])


  const getHomeTypes = () => {
    queryHomeTypeList().then((res: Common.Response.BaseListData<any>) => {
      if (res) {
        setHomeTypes(res.items)
      }
    })
  }
  /**
   * 
   * @param txType 体系类型，1=美术体系，2=书发体系，3=教培体系	4-客服中心
   */
  // const getSubjects = (txType: string) => {
  //   querySubjects({ pageNum: 1, pageSize: 100000, txType }).then((res: Common.Response.BaseListData<ISubject>) => {
  //     if (res) {
  //       const first = res.items.filter((i) => i.type === 0)
  //       const second = res.items.filter((i) => i.type === 1)

  //       if (txType == '1') {
  //         setPaintData([first, second])
  //       }
  //       if (txType == '2') {
  //         setShufaData([first, second])
  //       }
  //       if (txType == '3') {
  //         setJiaoPeiData([first, second])
  //       }
  //     }
  //   })
  // }

  const getSchoolIndex = (schoolId: number) => {
    const schoolIndex = schools.findIndex((i) => i.id == schoolId)
    return schoolIndex
  }

  const school = schools.length && schools[getSchoolIndex(schoolId)].schoolName

  const meishuFuzhu = homeTypes.find((item) => item.id == 1)
  const fuzhuVideos = meishuFuzhu ? meishuFuzhu.subjectTypeListVOList.filter((i) => i.type == 1) : []

  return (
    <View className="index container-white">
      {/**城市选择和搜索 */}
      <View className='at-row'
        style={{ marginBottom: '10rpx' }}>
        <IconFont size={40} name='didian01' color='orangered' />
        {
          schools.length ?
            <View className='at-row at-row__align--center' style={{ color: 'orangered' }}>
              <Picker
                mode="selector"
                value={getSchoolIndex(schoolId)}
                range={schools}
                onChange={(e) => {
                  setSchoolId(1)
                  const index = Number(e.detail.value)
                  setSchoolId(schools[index].id)
                  console.log(e)
                }}
                range-key="schoolName"
              >
                {school}
              </Picker>

              <IconFont name='right' size={30} color='orangered' />
            </View> : ''
        }

      </View>
      <View>
      </View>
      {/* 搜索框** */}
      {/* <View className='at-row'>
        <AtSearchBar placeholder='搜索课程或教学视频'
          value={searchValue}
          customStyle={{ width: '100%' }}
          onChange={(v) => setSearchValue(v)}
          onActionClick={handleActionClick} />
      </View> */}

      {/**banner */}
      <View className='at-row'>
        <SwiperContainer
          options={banners.map((i) => ({
            url: i.image,
            type: 1
          }))} auto={false} />
      </View>

      <View className='at-row icons' style={{ display: 'none' }}>
        {
          IConfigIcons.map((i) => (
            <View className='at-col at-col-3 box'
              onClick={() => {
                if (i.link) {
                  Taro.navigateTo({
                    url: i.link
                  })
                } else {
                  Taro.showToast({
                    title: '开发中',
                    icon: 'none'
                  })
                }
              }}
            >
              <Image src={i.icon} mode='widthFix' style={{ width: '70rpx' }} />
              <View>{i.name}</View>
            </View>
          ))
        }

      </View>

      {
        homeTypes.map((item, _index) => {
          return (
            <View className="index" key={_index} style={{
              display: item.subjectTypeListVOList.length > 0 ? "block" : 'none',
            }} >
              <View className='title'>{item.name}</View>
              <View className='at-row cards'>
                {
                  item.subjectTypeListVOList.map((i, index) => (
                    <View className='at-col at-col-4 card' key={index}
                      onClick={() => {
                        Taro.navigateTo({
                          url: `/packages/package-lesson-divide/index?id=${i.id}`
                        })
                      }}
                    >
                      <Image src={i.image} mode='widthFix' style={{ width: '100%' }} />
                    </View>
                  ))
                }
              </View>
            </View>
          )
        })
      }

      {
        fuzhuVideos.length > 0 &&
        <View className='title'>辅助视频</View>
      }
      <ScrollView scrollX>
        <View className='at-row'>
          {
            fuzhuVideos.map((i, index) => (
              <View
                className='at-col at-col-4 card'
                key={index}
                style={{ marginRight: 20, textAlign: 'center' }}
                onClick={() => {
                  Taro.navigateTo({
                    url: `/packages/package-lesson-divide/index?id=${i.id}`
                  })
                }}
              >
                <Image src={i.image} mode='widthFix' style={{ width: '100%' }} />
              </View>
            ))
          }
        </View>
      </ScrollView>

      <View className='title'>作品展示</View>
      {/* <View className='at-row cards'> */}
      <ScrollView scrollX>
        <View className='at-row'>
          {
            worksType.map((i, index) => (
              <View
                className='at-col at-col-5 card'
                key={index}
                style={{ marginRight: 20, textAlign: 'center' }}
                onClick={() => {
                  Taro.navigateTo({
                    // url: `/packages/package-lesson-divide/index?id=${i.id}`
                    url: `/packages/package-works/index?id=${i.id}&title=${i.name}`
                  })
                }}
              >
                <Image src={i.image} mode='widthFix' style={{ width: '100%' }} />
                <View>{i.name}</View>
              </View>
            ))
          }
        </View>
      </ScrollView>
      {/* </View> */}
    </View>
  );
}

export default Index;
